#include "BaseProcessor.h"
#include "Base/Log/LogDefine.h"


CBaseProcessor::CBaseProcessor(std::string name)
{
	mProcessorName = name;
	mThreadMessageFifo.init(4096);
	mProcessorType = PROCESSOR_TYPE::PROCESSOR_TYPE_NONE;
	self_mutex_init(&mThreadMessageLock);
}

CBaseProcessor::~CBaseProcessor()
{
	self_mutex_release(&mThreadMessageLock);
}

void CBaseProcessor::tick()
{
	handleThreadMessage();
	return ;
}

int CBaseProcessor::handleThreadMessage()
{
	for (int i = 0; i < 2000; i++)
	{
		CThreadMessage *msg = getOneThreadMessage();
		if (msg == nullptr)
		{
			break;;
		}

		this->dispatchThreadMessage(msg);

		SAFE_DELETE(msg);
	}

	return 0;
}

void CBaseProcessor::emptyThreadMessageHandle(CThreadMessage *msg)
{
	LOGW("msg id %d, no handle find, processor:%s", msg->getMessageID(), mProcessorName.c_str());
}

int CBaseProcessor::dispatchThreadMessage(CThreadMessage *msg)
{
	LOGW("call CBaseProcessor dispatch thread message");
	return 0;
}

bool CBaseProcessor::receiveThreadMessage(CThreadMessage *msg)
{
	if (msg == nullptr)
	{
		LOGW("receive thread message is null");
		return false;
	}

	if (!mThreadMessageFifo.put(msg))
	{
		LOGW("thread message fifo is full");
		AutoLock l(mThreadMessageLock);
		mThreadMessageCacheList.push_back(msg);
		return true;
	}

	return true;
}

CThreadMessage* CBaseProcessor::getOneThreadMessage()
{
	CThreadMessage *ret = nullptr;
	ret = mThreadMessageFifo.get();
	if (ret != nullptr)
	{
		return ret;
	}

	if (mThreadMessageCacheList.size() > 0)
	{
		AutoLock l(mThreadMessageLock);

		ret = mThreadMessageCacheList.front();
		mThreadMessageCacheList.pop_front();
		return ret;
	}

	return ret;
}

int CBaseProcessor::init()
{
	return 0;
}